#include <iostream>
#include <pthread.h>
#include <vector>
#include <unistd.h>
#include <string>
using namespace std;
const int pthreadnum = 5;

class Task
{
public:
    Task()
    {
    }
    void SetData(int x, int y)
    {
        datax = x;
        datay = y;
    }
    int add()
    {
        return datax + datay;
    }
    ~Task()
    {
    }

private:
    int datax;
    int datay;
};

class pthread : public Task
{
public:
    pthread(int x, int y, string& pthreadname)
        : _pthreadname(pthreadname)
    {
        _t.SetData(x, y);
    }

    string getname()
    {
        return _pthreadname;
    }
    int task()
    {
        return _t.add();
    }

    ~pthread()
    {
    }

private:
    string _pthreadname;
    Task _t;
};



class Result
{
public:
    Result()
    {}
    ~Result()
    {}
    void SetResult(int result, const std::string &threadname)
    {
        _result = result;
        _threadname = threadname;
    }
    void Print()
    {
        std::cout << _threadname << " : " << _result << std::endl;
    }
private:
    int _result;
    string _threadname;
};


void *handler(void *arg)
{
    pthread *p = static_cast<pthread *>(arg);
    string name = p->getname();
    int ret = p->task();

    Result * re = new Result();
    re->SetResult(ret,name);
    //cout << "name:" << name << "add ret:" << ret <<endl;

    delete p;
    return re;
}


int main()
{
    vector<pthread_t> pthreads;
    for (int i = 0; i < pthreadnum; i++)
    {
        char buffer[64];
        // char* buffer = new char[64];
        snprintf(buffer, 64, "pthread:%d", i + 1);
        string s(buffer);
        pthread *p = new pthread(10, 20, s);

        pthread_t tid;
        pthread_create(&tid, nullptr, handler, p);
        pthreads.push_back(tid);
    }

    void* ret = nullptr;
    vector<Result*> result;
    for (auto& e : pthreads)
    {
        //拿到线程运行结果
        pthread_join(e, &ret);
        result.push_back((Result*)ret);
    }

    for(auto& e : result)
    {
        e->Print();
        delete e;
    }
}






// void* handler(void* arg)
// {
//     const char* pthreadname = static_cast<char*>(arg);
//     while(1)
//     {
//         cout << "I am " <<pthreadname <<endl;
//         sleep(1);
//     }
//     delete [] pthreadname;
//     return nullptr;
// }